package cc.rengu.redp.common.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.util.Arrays;

/**
 * EasyExcel扩展
 * Excel导入导出时的数据字典自定义转换
 * 需配合注解ExcelCustomConvert使用
 *
 * @author xushitang
 */
public class CustomConverter implements Converter<String> {
    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(CellData cellData,
                                    ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        return cellData.getStringValue();
    }

    @Override
    public CellData convertToExcelData(String value,
                                       ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {
        ExcelCustomConvert ecc = contentProperty.getField().getAnnotation(ExcelCustomConvert.class);
        if (ecc == null) return new CellData(value);
        int index = Arrays.binarySearch(ecc.value(), value);
        if (index >= 0 && index < ecc.label().length) {
            return new CellData(ecc.label()[index]);
        } else {
            return new CellData(value);
        }
    }
}
